<template>
  <el-card>
    <template #header>
      <div class="u619_div">
        <span>学生管理</span>
      </div>
    </template>
    <el-card class="!border-none" shadow="never">
      <el-form
        ref="formRef"
        class="mb-[-16px]"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item>
          <el-input
            class="w-[280px] small_input"
            v-model="queryParams.keyword"
            placeholder="学号/姓名"
            clearable
            @keyup.enter="resetPage"
          />
        </el-form-item>

        <el-form-item>
          <el-cascader
            class="w-[300px] small_input"
            v-model="queryParams.college"
            @change="collegeChange"
            :options="data"
            placeholder="院系/班级"
          />
        </el-form-item>

        <el-form-item>
          <el-date-picker
            size="small"
            v-model="queryParams.value2"
            start-placeholder="选择开始时间"
            end-placeholder="选择结束时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            class="w-[300px] small_input_picker"
            placeholder="以创建时间范围筛选"
            @change="dateChange"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none" shadow="never">
      <el-button type="primary" @click="addUser">+ 添加学生</el-button>
      <el-button>+ 批量导入</el-button>
      <el-button>+ 下载模板</el-button>
      <el-button @click="handleBatchDelete">+ 批量删除</el-button>
      <el-table
        stripe
        class="mt-2"
        size="large"
        v-loading="pager.loading"
        :data="pager.lists"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="学号" prop="sn" min-width="120">
          <template #default="{ row }"> {{ row.student_no }} </template>
        </el-table-column>
        <el-table-column label="姓名" min-width="100">
          <template #default="{ row }"> {{ row.real_name }} </template>
        </el-table-column>
        <el-table-column label="所属院系" prop="nickname" min-width="120">
          <template #default="{ row }"> {{ row.college.name }} </template>
        </el-table-column>
        <el-table-column label="所属班级" prop="mobile" min-width="100">
          <template #default="{ row }"> {{ row.classes.name }} </template>
        </el-table-column>
        <el-table-column label="班级学生（人）" prop="email" min-width="140">
          <template #default="{ row }">
            {{ row.classes.student_num }}
          </template>
        </el-table-column>
        <el-table-column
          label="学生作品（个）"
          prop="inviter_name"
          min-width="140"
        >
          <template #default="{ row }">
            {{ row.classes.works_num }}
          </template>
        </el-table-column>
        <el-table-column label="账号状态" min-width="160">
          <template #default="{ row }">
            <span v-if="row.status === 1" style="color: #1abc9c">• 启用</span>
            <span v-else style="color: #f59a23">• 停用</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at" min-width="180">
          <template #default="{ row }">
            <div>{{ row.created_at }}</div>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="360" fixed="right">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-button
                class="custom-btn"
                plain
                type="primary"
                @click="gotoDeatil(row)"
              >
                <viewBtnIcon />
              </el-button>
              <el-button
                class="custom-btn"
                plain
                type="primary"
                @click="handleEdit(row)"
              >
                <deiltBtnIcon />
              </el-button>
              <el-button
                class="custom-btn custom-btn-stop"
                v-if="row.status == 1"
                type="primary"
                @click="BlackList(row)"
              >
                <stopBtnIcon />
              </el-button>
              <el-button
                type="primary"
                class="custom-btn custom-btn-start"
                v-if="row.status == 2"
                @click="BlackList(row)"
              >
                <startBtnIcon />
              </el-button>
              <el-button
                class="custom-btn"
                type="danger"
                plain
                @click="handleDelete(row)"
              >
                <delectBtnIcon />
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end mt-4">
        <pagination
          v-model="pager"
          @change="getLists"
          background="red"
          layout="prev, pager, next, sizes"
        />
      </div>
    </el-card>

    <add-user-pop
      v-if="popShow"
      ref="addUserPopRef"
      @close="popClose"
      @submit="popConfirm"
    />
  </el-card>
</template>
<script lang="ts" setup name="consumerLists">
import { usePaging } from "@/hooks/usePaging";
import {
  getStudentList,
  editStudent,
  getDepartmentList,
  delStudent,
} from "@/api/consumer";
import feedback from "@/utils/feedback";
import addUserPop from "../modals/addUserPop.vue";
import { useRequest } from "vue-hooks-plus";
import viewBtnIcon from "@/components/viewBtnIcon/index.vue";
import deiltBtnIcon from "@/components/deiltBtnIcon/index.vue";
import delectBtnIcon from "@/components/delectBtnIcon/index.vue";
import startBtnIcon from "@/components/startBtnIcon/index.vue";

const router = useRouter();

// 获取学院配置
const { data } = useRequest(async () => {
  const _Res = await getDepartmentList({
    page: 1,
    limit: 9999,
  });

  const list: any = [];

  _Res?.data?.forEach((_item) => {
    if (_item?.classes && _item?.classes?.length > 0) {
      list.push({
        value: _item.id,
        label: _item.name,
        children: _item?.classes?.map((_item2) => {
          return {
            value: _item2.id,
            label: _item2.name,
          };
        }),
      });
    }
  });

  return list;
});

//弹框ref
const addUserPopRef = shallowRef();
const popShow = ref(false);

const queryParams = reactive({
  keyword: "",
  created_start_date: "",
  created_end_date: "",
  college_id: "",
  classes_id: "",
  value2: "",
  college: "",
});

const collegeChange = (_data) => {
  queryParams.college_id = _data?.[0];
  queryParams.classes_id = _data?.[1];
};

const dateChange = (_data) => {
  queryParams.created_start_date = _data?.[0];
  queryParams.created_end_date = _data?.[1];
};

const isSelect = ref<number[]>([]);

const { pager, getLists, resetPage, resetParams } = usePaging({
  fetchFun: getStudentList,
  params: queryParams,
});
//打开创建用户弹框
const addUser = async () => {
  popShow.value = true;
  await nextTick();
  addUserPopRef.value.open();
  //   addUserPopRef.value.setFormData({
  //     nickname: "测试",
  //   });
};

// 编辑
const handleEdit = async (data: any) => {
  popShow.value = true;
  await nextTick();
  addUserPopRef.value.open();

  addUserPopRef.value.setFormData({
    ...data,
    password_confirm: data.password,
    status: data?.status === 1,
    college: [data?.college?.id, data?.classes?.id],
    id: data?.id,
  });
};

//删除
const handleDelete = async (data: any) => {
  await feedback.prompt(`是否确定删除该学生？`, `操作确认`, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputType: "textarea",
    inputPlaceholder: "请输入备注",
    callback: async ({ action, value }: any) => {
      if (action == "confirm") {
        console.log("确认了");
        try {
          await delStudent({ ids: data?.id, remark: value });

          getLists();
        } catch (error) {}
      } else {
      }
    },
    type: "warning",
  });
};

const handleBatchDelete = async () => {
  // 当前选中数据
  const _select = isSelect.value;
  await feedback.prompt(`是否确定删除选中学生？`, `操作确认`, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputType: "textarea",
    inputPlaceholder: "请输入备注",
    callback: async ({ action, value }: any) => {
      if (action == "confirm") {
        console.log("确认了");
        try {
          await delStudent({ ids: _select?.join(","), remark: value });

          getLists();
        } catch (error) {}
      } else {
      }
    },
    type: "warning",
  });
};

//黑名单
const BlackList = async (data) => {
  await feedback.prompt(
    `是否确定${data?.status == 1 ? "停用" : "启用"}该学生账号？`,
    `操作确认`,
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputType: "textarea",
      inputPlaceholder: "请输入备注",
      callback: async ({ action, value }: any) => {
        if (action == "confirm") {
          console.log("确认了");
          try {
            await editStudent({
              ...data,
              status: data.status === 1 ? 2 : 1,
              remark: value,
            });

            getLists();
          } catch (error) {}
        } else {
        }
      },
      type: "warning",
    }
  );
};

//多选
const handleSelectionChange = (value: any) => {
  isSelect.value = value.map((item: any) => item.id);
};

//弹框关闭
const popClose = () => {
  popShow.value = false;
};

const popConfirm = () => {
  getLists();
  popShow.value = false;
};

onActivated(() => {
  getLists();
});

getLists();

// 路由跳转
const gotoDeatil = (data) => {
  router.push(`/user/student/detail?id=${data?.id}`);
};
</script>

<style lang="scss" scoped></style>
